package com.csmk.springboot_simple.common;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;

public class CustomNumberDeserializer<T extends Number> extends JsonDeserializer<T> {
    private final Class<T> targetClass;

    public CustomNumberDeserializer(Class<T> targetClass) {
        this.targetClass = targetClass;
    }

    @Override
    public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String value = p.getText();
        try {
            if (targetClass.equals(Integer.class)) {
                return (T) Integer.valueOf(value);
            } else if (targetClass.equals(Long.class)) {
                return (T) Long.valueOf(value);
            }
        } catch (NumberFormatException e) {
            return null; // 转换失败时返回 null
        }
        throw new IllegalArgumentException("Unsupported number type: " + targetClass);
    }
}